using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using SmartHealthcare.Read.Api.Services;
using System.ComponentModel.DataAnnotations;
using static SmartHealthcare.Read.Api.Services.MedicineCostCalculationService;

namespace SmartHealthcare.Read.Api.Controllers
{
    /// <summary>
    /// 药品费用计算控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MedicineCostController : ControllerBase
    {
        private readonly MedicineCostCalculationService _medicineCostService;
        private readonly ILogger<MedicineCostController> _logger;

        public MedicineCostController(MedicineCostCalculationService medicineCostService, ILogger<MedicineCostController> logger)
        {
            _medicineCostService = medicineCostService;
            _logger = logger;
        }

        /// <summary>
        /// 计算单个药品费用
        /// </summary>
        /// <param name="medicineId">药品ID</param>
        /// <param name="quantity">数量</param>
        /// <param name="insuranceRatio">医保报销比例（0-100，默认0）</param>
        /// <returns>药品费用计算结果</returns>
        [HttpGet]
        public async Task<APIResult<MedicineCostResult>> CalculateSingleMedicineCost(
            [Required] long medicineId,
            [Required] [Range(1, int.MaxValue)] int quantity,
            [Range(0, 100)] decimal insuranceRatio = 0)
        {
            _logger.LogInformation($"接收到计算单个药品费用请求，药品ID：{medicineId}，数量：{quantity}，医保比例：{insuranceRatio}%");
            
            var result = await _medicineCostService.CalculateSingleMedicineCostAsync(medicineId, quantity, insuranceRatio);
            
            var apiResult = new APIResult<MedicineCostResult>();
            if (result.Success)
            {
                apiResult.Code = APIEnums.Success;
                apiResult.Msg = "药品费用计算成功";
                apiResult.Data = result;
            }
            else
            {
                apiResult.Code = APIEnums.Fail;
                apiResult.Msg = result.ErrorMessage;
            }
            
            return apiResult;
        }

        /// <summary>
        /// 计算多个药品的总费用
        /// </summary>
        /// <param name="request">药品费用计算请求</param>
        /// <returns>药品费用计算结果</returns>
        [HttpPost]
        public async Task<APIResult<MedicineCostResult>> CalculateMultipleMedicineCost([FromBody] MultipleMedicineCostRequest request)
        {
            _logger.LogInformation($"接收到计算多个药品费用请求，药品数量：{request.MedicineItems?.Count ?? 0}，医保比例：{request.InsuranceRatio}%");
            
            if (request.MedicineItems == null || !request.MedicineItems.Any())
            {
                return new APIResult<MedicineCostResult>
                {
                    Code = APIEnums.Fail,
                    Msg = "药品列表不能为空"
                };
            }

            var result = await _medicineCostService.CalculateMultipleMedicineCostAsync(request.MedicineItems, request.InsuranceRatio);
            
            var apiResult = new APIResult<MedicineCostResult>();
            if (result.Success)
            {
                apiResult.Code = APIEnums.Success;
                apiResult.Msg = "多个药品费用计算成功";
                apiResult.Data = result;
            }
            else
            {
                apiResult.Code = APIEnums.Fail;
                apiResult.Msg = result.ErrorMessage;
            }
            
            return apiResult;
        }

        /// <summary>
        /// 根据药品名称搜索并计算费用
        /// </summary>
        /// <param name="medicineName">药品名称（支持模糊搜索）</param>
        /// <param name="quantity">数量</param>
        /// <param name="insuranceRatio">医保报销比例（0-100，默认0）</param>
        /// <returns>药品费用计算结果列表</returns>
        [HttpGet]
        public async Task<APIResult<List<MedicineCostResult>>> CalculateMedicineCostByName(
            [Required] string medicineName,
            [Required] [Range(1, int.MaxValue)] int quantity,
            [Range(0, 100)] decimal insuranceRatio = 0)
        {
            _logger.LogInformation($"接收到根据药品名称搜索并计算费用请求，药品名称：{medicineName}，数量：{quantity}，医保比例：{insuranceRatio}%");
            
            var results = await _medicineCostService.CalculateMedicineCostByNameAsync(medicineName, quantity, insuranceRatio);
            
            var apiResult = new APIResult<List<MedicineCostResult>>();
            if (results.Any(r => r.Success))
            {
                apiResult.Code = APIEnums.Success;
                apiResult.Msg = "药品费用计算成功";
                apiResult.Data = results;
            }
            else
            {
                apiResult.Code = APIEnums.Fail;
                apiResult.Msg = results.FirstOrDefault()?.ErrorMessage ?? "未找到匹配的药品";
            }
            
            return apiResult;
        }

        /// <summary>
        /// 计算患者所有药品费用
        /// </summary>
        /// <param name="medicalCard">病人卡号</param>
        /// <param name="startDate">开始日期（可选，格式：yyyy-MM-dd）</param>
        /// <param name="endDate">结束日期（可选，格式：yyyy-MM-dd）</param>
        /// <returns>患者药品费用统计结果</returns>
        [HttpGet]
        public async Task<APIResult<PatientMedicineCostResult>> CalculatePatientMedicineCost(
            [Required] string medicalCard,
            string startDate = null,
            string endDate = null)
        {
            _logger.LogInformation($"接收到计算患者药品费用请求，病人卡号：{medicalCard}，时间范围：{startDate} 至 {endDate}");
            
            DateTime? start = null;
            DateTime? end = null;
            
            if (!string.IsNullOrEmpty(startDate))
            {
                if (!DateTime.TryParse(startDate, out var startDateTime))
                {
                    return new APIResult<PatientMedicineCostResult>
                    {
                        Code = APIEnums.Fail,
                        Msg = "开始日期格式不正确，请使用yyyy-MM-dd格式"
                    };
                }
                start = startDateTime;
            }
            
            if (!string.IsNullOrEmpty(endDate))
            {
                if (!DateTime.TryParse(endDate, out var endDateTime))
                {
                    return new APIResult<PatientMedicineCostResult>
                    {
                        Code = APIEnums.Fail,
                        Msg = "结束日期格式不正确，请使用yyyy-MM-dd格式"
                    };
                }
                end = endDateTime;
            }
            
            var result = await _medicineCostService.CalculatePatientMedicineCostAsync(medicalCard, start, end);
            
            var apiResult = new APIResult<PatientMedicineCostResult>();
            if (result.Success)
            {
                apiResult.Code = APIEnums.Success;
                apiResult.Msg = "患者药品费用计算成功";
                apiResult.Data = result;
            }
            else
            {
                apiResult.Code = APIEnums.Fail;
                apiResult.Msg = result.ErrorMessage;
            }
            
            return apiResult;
        }

        /// <summary>
        /// 验证药品价格是否合理
        /// </summary>
        /// <param name="medicineId">药品ID</param>
        /// <param name="unitPrice">单价</param>
        /// <returns>价格验证结果</returns>
        [HttpGet]
        public async Task<APIResult<PriceValidationResult>> ValidateMedicinePrice(
            [Required] long medicineId,
            [Required] [Range(0.01, double.MaxValue)] decimal unitPrice)
        {
            _logger.LogInformation($"接收到验证药品价格请求，药品ID：{medicineId}，单价：{unitPrice}");
            
            var result = await _medicineCostService.ValidateMedicinePriceAsync(medicineId, unitPrice);
            
            var apiResult = new APIResult<PriceValidationResult>();
            if (result.IsValid)
            {
                apiResult.Code = APIEnums.Success;
                apiResult.Msg = "药品价格验证通过";
                apiResult.Data = result;
            }
            else
            {
                apiResult.Code = APIEnums.Fail;
                apiResult.Msg = result.ErrorMessage;
                apiResult.Data = result;
            }
            
            return apiResult;
        }
    }
} 